package com.maxlen.scheduled;

import com.maxlen.constant.RedisConstant;
import com.maxlen.entity.service.SeckillService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 秒杀商品的定时上架：
 *  每天晚上 3 点：上架最近三天需要秒杀的商品
 *  当天 00:00:00 - 23:59:59
 *  明天 00:00:00 - 23:59:59
 *  后天 00:00:00 - 23:59:59
 */
@Component
@EnableScheduling // 开启定时任务
public class SeckillSkuScheduled {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void uploadSeckillSkuLatest3Days(){
        // 分布式锁
        RLock lock = redissonClient.getLock(RedisConstant.UPLOAD_LOCK);
        lock.lock();
        try{
            // 上架秒杀商品
            System.out.println("开始自动上架秒杀商品");
            seckillService.uploadSeckillSkuLatest3Days();
        }finally {
            lock.unlock();
        }
    }

}
